<?php
namespace app\common\model;

use think\facade\Cache;
use hema\wechat\Driver as Wechat;

/**
 * 公众号模型
 */
class Setting extends BaseModel
{
    // 定义表名
    protected $name = 'setting';
    protected $createTime = false;

    // 追加字段
    protected $append = [];

    /**
     * 设置项描述
     */
    private $describe = [
        'web' => '站点设置',
        'ability' => '功能设置',
        'divide' => '分佣设置值',
        'wxweb' => '网站应用',
        'wxpayisp' => '微信支付服务商设置',
        'webpay' => '支付设置',
        'wxpay' => '微信支付',
        'webtplmsg' => '站点模板消息',
        'subscribe' => '关注回复',//公众号
        'menus' => '公众号菜单',
        'wxopen' => '微信第三方平台',
        'sms' => '短信平台',
        'passport' => '登录注册'
    ];

    /**
     * 获取器: 转义数组格式
     */
    public function getValuesAttr($value)
    {
        return json_decode($value, true);
    }

    /**
     * 修改器: 转义成json格式
     */
    public function setValuesAttr($value)
    {
        return json_encode($value);
    }

    /**
     * 获取指定项设置
     */
    public static function getItem(string $key, $applet_id = 0)
    {
        $data = self::getAll($applet_id);
        return isset($data[$key]) ? $data[$key]['values'] : [];
    }

    /**
     * 获取设置项信息
     */
    public static function detail(string $key,$applet_id = 0)
    {
        // 筛选条件
        $filter = [];
        $filter['key'] = $key;
        $filter['applet_id'] = $applet_id;
        return self::where($filter)->find();
    }

    /**
     * 全局缓存: 系统设置
     */
    public static function getAll($applet_id = 0)
    {
        $self = new static;
        // 筛选条件
        $filter = [];
        $filter['applet_id'] = $applet_id;
        if (!$data = Cache::get('setting_' . $applet_id)) {
            $data = array_column($self::where($filter)->select()->toArray(), null, 'key');
            Cache::set('setting_' . $applet_id, $data);
        }
        return array_merge_multiple($self->defaultData(), $data);
    }

    /**
     * 更新系统设置
     */
    public function edit(string $key, array $values, $applet_id = 0)
    {
        //微信第三方平台
        if($key == 'wxopen'){
            $wx = new Wechat;
        	$wx->startTicket($values['app_id'],$values['app_secret']);
        }
        //公众号菜单
        if($key == 'menus'){
            $wx = new Wechat;
            $result = $wx->creatMenu($values,$applet_id);
            if($result['errcode'] != 0){
                $this->error = 'code：' . $result['errcode'] . '，msg：' . $result['errmsg'];
                return false;
            }
        }
        //关注公众号回复
        if($key == 'subscribe'){
            $values = $this->subscribe($values);
        }
        $model = self::detail($key,$applet_id) ?: $this;
        // 删除系统设置缓存
        Cache::delete('setting_' . $applet_id);
        return $model->save([
            'key' => $key,
            'describe' => $this->describe[$key],
            'values' => $values,
            'applet_id' => $applet_id,
        ]) !== false;
    }

    /**
     * 关注回复内容
     */
    private function subscribe($data)
    {
        if($data['type'] != 'text'){
            if(!$material = Material::mediaId($data['content']['media_id'])){
                $this->error = '素材不存在';
                return false; 
            }
            //视频消息
            if($data['type'] == 'video'){
                //获取视频素材内容
                $data['content']['title'] = $material['name'];
                $data['content']['description'] = $material['introduction'];
            }
            //图文消息
            if($data['type'] == 'news'){
                $data['content']['article_count'] = sizeof($material['text']);
                $item = [];
                foreach ($material['text'] as $vo){
                    $item[] = [
                        'title' => $vo['title'],
                        'description' => $vo['digest'],
                        'pic_url' => $vo['url'],
                        'url' => $vo['content_source_url'],
                    ];
                }
                $data['content']['articles'] = $item;
            }
        }
        return $data;
    }

    /**
     * 默认配置
     */
    public function defaultData()
    {
        return [
            'web' => [
                'key' => 'web',
                'describe' => '站点设置',
                'values' => [
                    'name' => '河马云店',//网站名称
                    'icp' => '',    //备案号
                    'address' => '',//地址
                    'keywords' => '',   //关键字
                    'description' => '',    //描述
                    'company' => '',//公司名称
                    'phone' => '',//联系电话
                    'baidu_count' => '',//百度统计
                    'qq' => '',//在线QQ
                    'wechat' => '',//微信
                ],
            ],
            'passport' => [
                'key' => 'passport',
                'describe' => '登录注册',
                'values' => [
                    'login' => [
                        'wechat' => 0,//关注微信公众号
                        'scan' => 0,//扫码登录
                        'phone' => 0,//手机验证码
                        'user_name' => 1,//账号密码
                    ],
                    'register' => [
                        'wechat' => 0,//关注微信公众号
                        'scan' => 0,//扫码登录
                        'phone' => 0,//手机验证码
                    ],
                ],
            ],
            'ability' => [
                'key' => 'ability',
                'describe' => '功能设置',
                'values' => [
                    'applet_apply' => 1,//小程序申请是否需要审核
                    'applet_fee' => 0,//小程序审核费0不收取
                    'applet_online' => 1,//小程序发布是否自动上线
                    'pay_apply' => 1,//支付申请是否需要审核
                    
                    'open_id' => '', //管理员微信ID
                    'wxmap' => '', //微信地图KEY
                ],
            ],
            'wxopen' => [
                'key' => 'wxopen',
                'describe' => '微信第三方平台',
                'values' => [
                    'app_id' => '', //APPID
                    'app_secret' => '', //密钥
                    'token' => '',
                    'encoding_aes_key' => '',
                    'api_domain' => '',
                    'authorize_domain' => '',
                ],
            ],
            'wxweb' => [
                'key' => 'wxweb',
                'describe' => '微信网站应用',
                'values' => [
                    'app_id' => '', //APPID
                    'app_secret' => '', //密钥
                ],
            ],
            'wxpayisp' => [
                'key' => 'wxpayisp',
                'describe' => '微信支付服务商设置',
                'values' => [
                    'app_id' => '', //公众号APPID
                    'mch_id' => '',  //商户号
                    'api_key' => '', //APIv3密钥
                    'api_serial_no' => '',//API证书序列号
                    'cert_pem' => '',//API公钥证书
                    'key_pem' => '',//API私钥证书
                    'serial_no' => '',//平台证书序列号
                    'certificates' => '',//平台证书
                    'expire_time' => 0,//平台证书到期时间
                ],
            ],
            'webpay' => [
                'key' => 'webpay',
                'describe' => '支付设置',
                'values' => [
                    'cost' => [
                        'cash_mode' => 'fixed',//用户提现手续费模式 fixed=固定 ratio=比例 
                        'cash_fee' => 0,//手续费数值
                        'applet_fee' => 0,//小程序审核费0不收取
                    ],
                    'wx' => [
                        'name' => '',//商户全称
                        'app_id' => '', //微信应用
                        'mch_id' => '',//商户号
                        'api_key' => '', //APIv3密钥
                        'api_serial_no' => '',//API证书序列号
                        'is_sub' => 0,
                        'cert_pem' => '', //apiclient_cert.pem 证书
                        'key_pem' => '', //apiclient_key.pem 密钥
                        'serial_no' => '',//平台证书序列号
                        'certificates' => '',//平台证书
                        'expire_time' => 0,//平台证书到期时间
                    ]
                ]
            ],
            'divide' => [
                'key' => 'divide',
                'describe' => '分佣设置',
                'values' => [
                    'extract' => 0,//抽取比例0-30，单位百分，0为不抽取
                    'agent_extract' => 0,//抽取分账总额的百分比，0-100，0为不抽取，100抽取全部。
                ]
            ],
            'wxpay' => [
                'key' => 'wxpay',
                'describe' => '微信支付',
                'values' => [
                    'app_id' => '', //微信应用
                    'is_sub' => 0, //是否为特约商户
                    'mch_id' => '',//商户号
                    'api_key' => '', //APIv3密钥
                    'api_serial_no' => '',//API证书序列号
                    'cert_pem' => '', //apiclient_cert.pem 证书
                    'key_pem' => '', //apiclient_key.pem 密钥
                    'serial_no' => '',//平台证书序列号
                    'certificates' => '',//平台证书
                    'expire_time' => 0,//平台证书到期时间
                ]
            ],
            'webtplmsg' => [
                'key' => 'webtplmsg',
                'describe' => '模板消息',
                'values' => [
                    'new_order' => '',    //新订单通知
                    'examine' => '',  //审核状态通知
                    'balance' => '',  //账户资金变动提醒
                    'apply' => '',    //申请受理通知
                    'deduction' => '',    //扣费失败通知
                    'testing' => '',  //试用申请成功通知
                    'refund' => '',   //退款发起通知
                    'grab' => '',   //骑手抢单通知
                ],
            ],
            'menus' => [
                'key' => 'menus',
                'describe' => '公众号菜单',
                'values' => [
                /*  0 => [
                        "type" => "view",
                        "name" => "一级菜单",
                        "sub_button" => [
                            0 => [
                                "type" => "click",
                                "name" => "二级菜单",
                                "key" => "关键字"
                            ],
                        ],
                        "url" => base_url()
                    ]*/
                ],
            ],
            'subscribe' => [
                'key' => 'subscribe',
                'describe' => '关注回复',
                'values' => [
                    'is_open' => 1,     //是否开启 0=关闭，1=开启
                    'type' => 'text',   //消息类型 text=文字消息,image=图片消息,news=图文消息,voice=声音消息
                    'content' => [
                        'text' => '',//回复文字
                        'media_id' => '',//素材
                    ]
                ]
            ],
            'sms' => [
                'key' => 'sms',
                'describe' => '短信平台',
                'values' => [
                    'gateway' => '',     //短信平台
                    'scene' => [
                        'captcha' => 0,//验证码
                    ]
                ]
            ],
        ];
    }

}
